import React, { useState } from "react";
import "./index.css";
import {
  Table,
  Input,
  message,
  Popconfirm,
  Form,
  Typography,
  Button,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";

const originData = [
  {
    key: "1",
    action: "query",
    name: "查询列表",
    describe: "查询列表",
  },
  {
    key: "2",
    action: "query",
    name: "查询明细",
    describe: "查询明细",
  },
  {
    key: "3",
    action: "add",
    name: "新增",
    describe: "新增",
  },
  {
    key: "4",
    action: "update",
    name: "修改",
    describe: "修改",
  },
  {
    key: "5",
    action: "delete",
    name: "删除",
    describe: "删除",
  },
  {
    key: "6",
    action: "import",
    name: "导入",
    describe: "导入",
  },
  {
    key: "7",
    action: "export",
    name: "导出",
    describe: "导出",
  },
];

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const EditableTable = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState("");
  const [count, setCount] = useState(8);

  const isEditing = (record) => record.key === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      action: "",
      name: "",
      describe: "",
      ...record,
    });
    setEditingKey(record.key);
  };

  const deleteRow = (key) => {
    const dataList = [...data];
    const newData = dataList.filter((item) => item.key !== key);
    setData(newData);
    message.success("删除成功");
  };

  const cancel = () => {
    setEditingKey("");
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const handleAdd = () => {
    const newRow = {
      key: count,
      action: "",
      name: "",
      describe: "",
    };
    setEditingKey(count);
    const newData = [newRow, ...data];
    setData(newData);
    setCount(count + 1);
  };

  const columns = [
    {
      title: "操作类型",
      dataIndex: "action",
      width: "20%",
      editable: true,
    },
    {
      title: "名称",
      dataIndex: "name",
      width: "20%",
      editable: true,
    },
    {
      title: "描述",
      dataIndex: "describe",
      width: "20%",
      editable: true,
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <Popconfirm
              title="确定取消?"
              okText="确认"
              cancelText="取消"
              onConfirm={cancel}
            >
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
              style={{ marginRight: 10 }}
            >
              编辑
            </Typography.Link>
            |
            <Popconfirm
              title="确认删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => deleteRow(record.key)}
            >
              <a style={{ marginLeft: 10 }}>删除</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <Form form={form} component={false}>
      <Button
        icon={<PlusOutlined />}
        type="primary"
        onClick={handleAdd}
        style={{ marginBottom: 10 }}
      >
        新增一行
      </Button>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{
          onChange: cancel,
        }}
      />
    </Form>
  );
};

export default EditableTable;
